package com.oolee.cloud.controller;


import com.oolee.cloud.entity.Payment;
import com.oolee.cloud.general.GeneralResult;
import com.oolee.cloud.lb.MyLoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/cloud";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private MyLoadBalancer myLoadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/consumer/payment/create")
    public GeneralResult<Integer> create(Payment payment){
        log.info("prepare to going to provider...");
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,GeneralResult.class);
    }

    @GetMapping(value = "/consumer/payment/get/{id}")
    public GeneralResult<Integer> getPaymentById(@PathVariable("id")Long id){
        log.info("prepare to going to provider...get id"+id);
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,GeneralResult.class);
    }


    @GetMapping(value = "/consumer/payment/getInstance/{id}")
    public GeneralResult<Integer> getPaymentByInstance(@PathVariable("id")Long id){
        //获取所有服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances == null || instances.size() <= 0){
            return null;
        }
        //根据我们的轮询算法得到对应的服务实例
        ServiceInstance instance = myLoadBalancer.getInstance(instances);
        //根据服务实例获得服务器的uri
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri+"cloud/payment/get/"+id,GeneralResult.class);
    }
}
